/**
 * Markdown 渲染工具
 * 使用 highlight.js 实现代码高亮
 */

import hljs from 'highlight.js'

/**
 * 解析 Markdown 为 HTML
 * 使用增强的正则表达式 + highlight.js 代码高亮
 */
export function parseMarkdown(markdown) {
  if (!markdown) return ''

  let html = markdown

  // 存储代码块，避免被其他规则干扰
  const codeBlocks = []

  // 1. 提取并高亮代码块
  html = html.replace(/```([\w]*)\r?\n([\s\S]*?)```/g, (match, lang, code) => {
    const index = codeBlocks.length
    let highlightedCode = ''

    try {
      // 使用 highlight.js 进行代码高亮
      if (lang && hljs.getLanguage(lang)) {
        highlightedCode = hljs.highlight(code.trim(), { language: lang }).value
      } else {
        highlightedCode = hljs.highlightAuto(code.trim()).value
      }
    } catch (e) {
      // 如果高亮失败，使用转义的纯文本
      highlightedCode = escapeHtml(code.trim())
    }

    codeBlocks.push(`<pre><code class="hljs language-${lang || 'plaintext'}">${highlightedCode}</code></pre>`)
    return `{{CODEBLOCK${index}}}`
  })

  // 2. 提取并保护行内代码
  const inlineCodes = []
  html = html.replace(/`([^`\n]+?)`/g, (match, code) => {
    const index = inlineCodes.length
    inlineCodes.push(`<code>${escapeHtml(code)}</code>`)
    return `{{INLINECODE${index}}}`
  })

  // 3. 转义 HTML 特殊字符
  html = escapeHtml(html)

  // 4. 处理标题
  html = html.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
  html = html.replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
  html = html.replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
  html = html.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
  html = html.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
  html = html.replace(/^#\s+(.+)$/gm, '<h1>$1</h1>')

  // 5. 处理图片（必须在链接之前）
  html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" />')

  // 6. 处理链接
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')

  // 7. 处理粗体
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  html = html.replace(/__(.+?)__/g, '<strong>$1</strong>')

  // 8. 处理斜体
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>')
  html = html.replace(/_(.+?)_/g, '<em>$1</em>')

  // 9. 处理删除线
  html = html.replace(/~~(.+?)~~/g, '<del>$1</del>')

  // 10. 处理分割线
  html = html.replace(/^[-*_]{3,}$/gm, '<hr>')

  // 11. 处理引用
  html = html.replace(/^&gt;\s*(.+)$/gm, '<blockquote>$1</blockquote>')
  html = html.replace(/<\/blockquote>\n<blockquote>/g, '\n')

  // 12. 处理无序列表
  html = html.replace(/^[-*+]\s+(.+)$/gm, '<li>$1</li>')

  // 13. 处理有序列表
  html = html.replace(/^\d+\.\s+(.+)$/gm, '<li class="ordered">$1</li>')

  // 14. 处理任务列表
  html = html.replace(/<li>\[ \]\s*(.+)<\/li>/g, '<li class="task-list">☐ $1</li>')
  html = html.replace(/<li>\[x\]\s*(.+)<\/li>/gi, '<li class="task-list checked">☑ $1</li>')

  // 15. 处理表格
  html = parseTable(html)

  // 16. 处理换行和段落
  html = processLines(html)

  // 17. 恢复代码块
  codeBlocks.forEach((code, index) => {
    html = html.replace(`{{CODEBLOCK${index}}}`, code)
  })

  // 18. 恢复行内代码
  inlineCodes.forEach((code, index) => {
    html = html.replace(`{{INLINECODE${index}}}`, code)
  })

  return html
}

/**
 * 处理表格
 */
function parseTable(text) {
  const lines = text.split('\n')
  const result = []
  let inTable = false
  let tableRows = []

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()

    // 检测表格行（包含 | 符号）
    if (line.includes('|') && !line.startsWith('<')) {
      const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell)

      // 检查是否是分隔行（如 |---|---|）
      if (cells.every(cell => /^[-:]+$/.test(cell))) {
        // 这是表头分隔行，跳过
        continue
      }

      if (!inTable) {
        inTable = true
        tableRows = []
      }

      const cellType = tableRows.length === 0 ? 'th' : 'td'
      const row = `<tr>${cells.map(cell => `<${cellType}>${cell}</${cellType}>`).join('')}</tr>`
      tableRows.push(row)
    } else {
      // 结束表格
      if (inTable && tableRows.length > 0) {
        const tableHtml = `<table><tbody>${tableRows.join('')}</tbody></table>`
        result.push(tableHtml)
        tableRows = []
        inTable = false
      }
      result.push(line)
    }
  }

  // 处理最后的表格
  if (inTable && tableRows.length > 0) {
    const tableHtml = `<table><tbody>${tableRows.join('')}</tbody></table>`
    result.push(tableHtml)
  }

  return result.join('\n')
}

/**
 * 处理行和段落
 */
function processLines(text) {
  const lines = text.split('\n')
  const result = []
  let currentParagraph = []
  let inList = false

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()

    // 空行
    if (!line) {
      if (currentParagraph.length > 0) {
        result.push(`<p>${currentParagraph.join(' ')}</p>`)
        currentParagraph = []
      }
      inList = false
      continue
    }

    // HTML 标签行
    if (line.match(/^<(h[1-6]|blockquote|hr|img|pre|table)|^{{CODEBLOCK/)) {
      if (currentParagraph.length > 0) {
        result.push(`<p>${currentParagraph.join(' ')}</p>`)
        currentParagraph = []
      }
      result.push(line)
      inList = false
      continue
    }

    // 列表项
    if (line.match(/^<li/)) {
      if (currentParagraph.length > 0) {
        result.push(`<p>${currentParagraph.join(' ')}</p>`)
        currentParagraph = []
      }

      const isOrdered = line.includes('class="ordered"')
      const listTag = isOrdered ? 'ol' : 'ul'

      if (!inList) {
        result.push(`<${listTag}>`)
        inList = listTag
      } else if (inList !== listTag) {
        result.push(`</${inList}>`)
        result.push(`<${listTag}>`)
        inList = listTag
      }

      result.push(line.replace(' class="ordered"', ''))
      continue
    }

    // 结束列表
    if (inList) {
      result.push(`</${inList}>`)
      inList = false
    }

    // 普通文本行
    currentParagraph.push(line)
  }

  // 处理最后的段落或列表
  if (currentParagraph.length > 0) {
    result.push(`<p>${currentParagraph.join(' ')}</p>`)
  }
  if (inList) {
    result.push(`</${inList}>`)
  }

  return result.join('\n')
}

/**
 * HTML 转义函数
 */
function escapeHtml(text) {
  const htmlMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  }
  return text.replace(/[&<>"']/g, char => htmlMap[char])
}
